import express from "express";
import { ObjectId } from "mongodb";
import authMiddleware from "../middleware/auth.js";
import { getDb } from "../config/database.js";

const router = express.Router();
const COLLECTION = "shops";

// 获取店铺列表
router.get("/", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const {
      page = 1,
      limit = 10,
      search = "",
      platform = "",
      customerId = "",
    } = req.query;
    const skip = (Number(page) - 1) * Number(limit);

    // 构建查询条件
    const query = {};

    if (search) {
      query.$or = [
        { shopName: { $regex: search, $options: "i" } },
        { shopId: { $regex: search, $options: "i" } },
        { customerName: { $regex: search, $options: "i" } },
      ];
    }

    if (platform) {
      query.platform = platform;
    }

    if (customerId) {
      query.customerId = new ObjectId(customerId);
    }

    // 聚合查询，关联客户信息
    const pipeline = [
      { $match: query },
      {
        $lookup: {
          from: "customers",
          localField: "customerId",
          foreignField: "_id",
          as: "customer",
        },
      },
      {
        $addFields: {
          customerName: { $arrayElemAt: ["$customer.name", 0] },
        },
      },
      { $project: { customer: 0 } },
      { $sort: { createdAt: -1 } },
      { $skip: skip },
      { $limit: Number(limit) },
    ];

    const shops = await db.collection(COLLECTION).aggregate(pipeline).toArray();

    // 获取总数
    const countPipeline = [
      { $match: query },
      {
        $lookup: {
          from: "customers",
          localField: "customerId",
          foreignField: "_id",
          as: "customer",
        },
      },
      {
        $addFields: {
          customerName: { $arrayElemAt: ["$customer.name", 0] },
        },
      },
      { $count: "total" },
    ];

    const countResult = await db
      .collection(COLLECTION)
      .aggregate(countPipeline)
      .toArray();
    const total = countResult.length > 0 ? countResult[0].total : 0;

    res.json({
      shops,
      total,
      page: Number(page),
      limit: Number(limit),
      totalPages: Math.ceil(total / Number(limit)),
    });
  } catch (error) {
    console.error("获取店铺列表失败:", error);
    res.status(500).json({ error: "获取店铺列表失败" });
  }
});

// 创建店铺
router.post("/", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const { shopName, shopId, customerId, platform, expressCompanies } =
      req.body;

    // 验证必填字段
    if (
      !shopName ||
      !shopId ||
      !customerId ||
      !platform ||
      !expressCompanies ||
      expressCompanies.length === 0
    ) {
      return res.status(400).json({ error: "所有字段都为必填项" });
    }

    // 检查店铺ID是否已存在
    const existingShop = await db.collection(COLLECTION).findOne({ shopId });
    if (existingShop) {
      return res.status(400).json({
        error: `店铺ID "${shopId}" 已存在，请使用其他ID`,
      });
    }

    // 验证客户是否存在
    const customer = await db
      .collection("customers")
      .findOne({ _id: new ObjectId(customerId) });
    if (!customer) {
      return res.status(400).json({ error: "所选客户不存在" });
    }

    // 创建新店铺
    const newShop = {
      shopName,
      shopId,
      customerId: new ObjectId(customerId),
      customerName: customer.name,
      platform,
      expressCompanies,
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    const result = await db.collection(COLLECTION).insertOne(newShop);
    newShop._id = result.insertedId;

    res.status(201).json(newShop);
  } catch (error) {
    console.error("创建店铺失败:", error);

    // 处理唯一索引冲突错误
    if (error.code === 11000) {
      return res.status(400).json({
        error: `店铺ID "${req.body.shopId}" 已存在，请使用其他ID`,
      });
    }

    res.status(500).json({ error: "创建店铺失败" });
  }
});

// 更新店铺
router.put("/:id", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const { id } = req.params;
    const { shopName, shopId, customerId, platform, expressCompanies } =
      req.body;

    // 验证必填字段
    if (
      !shopName ||
      !shopId ||
      !customerId ||
      !platform ||
      !expressCompanies ||
      expressCompanies.length === 0
    ) {
      return res.status(400).json({ error: "所有字段都为必填项" });
    }

    // 检查店铺ID是否已被其他店铺使用
    const existingShop = await db.collection(COLLECTION).findOne({
      shopId,
      _id: { $ne: new ObjectId(id) },
    });

    if (existingShop) {
      return res.status(400).json({
        error: `店铺ID "${shopId}" 已被其他店铺使用`,
      });
    }

    // 验证客户是否存在
    const customer = await db
      .collection("customers")
      .findOne({ _id: new ObjectId(customerId) });
    if (!customer) {
      return res.status(400).json({ error: "所选客户不存在" });
    }

    // 更新店铺
    const updateData = {
      $set: {
        shopName,
        shopId,
        customerId: new ObjectId(customerId),
        customerName: customer.name,
        platform,
        expressCompanies,
        updatedAt: new Date(),
      },
    };

    const result = await db
      .collection(COLLECTION)
      .findOneAndUpdate({ _id: new ObjectId(id) }, updateData, {
        returnDocument: "after",
      });

    if (!result) {
      return res.status(404).json({ error: "店铺不存在" });
    }

    res.json(result);
  } catch (error) {
    console.error("更新店铺失败:", error);

    // 处理唯一索引冲突错误
    if (error.code === 11000) {
      return res.status(400).json({
        error: `店铺ID "${req.body.shopId}" 已被其他店铺使用`,
      });
    }

    res.status(500).json({ error: "更新店铺失败" });
  }
});

// 获取单个店铺
router.get("/:id", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const pipeline = [
      { $match: { _id: new ObjectId(req.params.id) } },
      {
        $lookup: {
          from: "customers",
          localField: "customerId",
          foreignField: "_id",
          as: "customer",
        },
      },
      {
        $addFields: {
          customerName: { $arrayElemAt: ["$customer.name", 0] },
        },
      },
      { $project: { customer: 0 } },
    ];

    const shops = await db.collection(COLLECTION).aggregate(pipeline).toArray();
    const shop = shops[0];

    if (!shop) {
      return res.status(404).json({ error: "店铺不存在" });
    }

    res.json(shop);
  } catch (error) {
    console.error("获取店铺失败:", error);
    res.status(500).json({ error: "获取店铺失败" });
  }
});

// 删除店铺
router.delete("/:id", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const result = await db
      .collection(COLLECTION)
      .findOneAndDelete({ _id: new ObjectId(req.params.id) });

    if (!result) {
      return res.status(404).json({ error: "店铺不存在" });
    }

    res.json({ message: "店铺删除成功" });
  } catch (error) {
    console.error("删除店铺失败:", error);
    res.status(500).json({ error: "删除店铺失败" });
  }
});

// 根据客户ID获取店铺列表
router.get("/customer/:customerId", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const { customerId } = req.params;

    const shops = await db
      .collection(COLLECTION)
      .find({ customerId: new ObjectId(customerId) })
      .sort({ createdAt: -1 })
      .toArray();

    res.json({ shops });
  } catch (error) {
    console.error("获取客户店铺失败:", error);
    res.status(500).json({ error: "获取客户店铺失败" });
  }
});

export default router;
